using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 用于确保UI在不同屏幕尺寸下正确缩放的组件
/// 添加到所有主要Canvas对象上
/// </summary>
public class UIScaler : MonoBehaviour
{
    [Header("缩放设置")]
    [Tooltip("UI设计的参考分辨率宽度")]
    public float referenceWidth = 1920f;
    
    [Tooltip("UI设计的参考分辨率高度")]
    public float referenceHeight = 1080f;
    
    [Tooltip("是否在启动时自动应用缩放")]
    public bool applyOnStart = true;
    
    [Tooltip("是否根据宽度或高度计算缩放")]
    public bool matchWidthOrHeight = true;
    
    [Range(0, 1)]
    [Tooltip("0=匹配宽度, 1=匹配高度")]
    public float matchValue = 0.5f;
    
    private CanvasScaler canvasScaler;
    
    private void Awake()
    {
        canvasScaler = GetComponent<CanvasScaler>();
        if (canvasScaler == null)
        {
            Debug.LogError("[UIScaler] 无法找到CanvasScaler组件!");
            canvasScaler = gameObject.AddComponent<CanvasScaler>();
        }
        
        Debug.Log($"[UIScaler] 初始化, 设备屏幕尺寸: {Screen.width}x{Screen.height}");
    }
    
    private void Start()
    {
        if (applyOnStart)
        {
            ApplyScaling();
        }
    }
    
    /// <summary>
    /// 应用UI缩放设置
    /// </summary>
    public void ApplyScaling()
    {
        if (canvasScaler != null)
        {
            // 设置Canvas Scaler为Scale With Screen Size模式
            canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            
            // 设置参考分辨率
            canvasScaler.referenceResolution = new Vector2(referenceWidth, referenceHeight);
            
            // 设置屏幕匹配模式
            canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
            
            // 设置宽高匹配值
            canvasScaler.matchWidthOrHeight = matchValue;
            
            Debug.Log($"[UIScaler] 已应用UI缩放: 参考分辨率={referenceWidth}x{referenceHeight}, " +
                      $"匹配值={matchValue}, 当前设备={Screen.width}x{Screen.height}");
        }
    }
    
    /// <summary>
    /// 在游戏运行时调整UI缩放
    /// </summary>
    public void AdjustScaling(float newMatchValue)
    {
        matchValue = Mathf.Clamp01(newMatchValue);
        if (canvasScaler != null)
        {
            canvasScaler.matchWidthOrHeight = matchValue;
            Debug.Log($"[UIScaler] 调整UI缩放匹配值: {matchValue}");
        }
    }
    
    /// <summary>
    /// 通过设备方向自动优化缩放
    /// </summary>
    public void OptimizeForDeviceOrientation()
    {
        // 根据设备方向和屏幕宽高比自动调整匹配值
        float aspectRatio = (float)Screen.width / Screen.height;
        
        if (aspectRatio > 1.7f)  // 宽屏设备
        {
            matchValue = 0.5f;  // 平衡宽高匹配
        }
        else if (aspectRatio < 1.5f)  // 窄屏设备
        {
            matchValue = 0.0f;  // 优先匹配宽度
        }
        else
        {
            matchValue = 0.3f;  // 默认值
        }
        
        if (canvasScaler != null)
        {
            canvasScaler.matchWidthOrHeight = matchValue;
            Debug.Log($"[UIScaler] 自动优化UI缩放: 屏幕比例={aspectRatio:F2}, 匹配值={matchValue}");
        }
    }
} 